package com.proposition.commons.exam.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URISyntaxException;
import java.util.Enumeration;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * 其实docx属于zip的一种，这里只需要操作word/document.xml中的数据，其他的数据不用动
 *
 * @author yigehui
 */
public class ExamExportUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExamExportUtil.class);

    /**
     * @throws ZipException
     * @throws IOException
     */

    public String outDocx(String ftlTemplateName, Map dataMap, HttpServletRequest request) throws ZipException, IOException, URISyntaxException, TemplateException {

        //获取模板
        //创建配置实例
        Configuration configuration = new Configuration();
        //设置编码
        configuration.setDefaultEncoding("UTF-8");

	    configuration.setClassForTemplateLoading(ExamExportUtil.class,"/static/exam-template/export/");
        //获取模板
        Template template = configuration.getTemplate(ftlTemplateName);


        //输出文件
        String outTempFtlFilePath = request.getServletContext().getRealPath("/export/upload/emp/docx/temp.ftl");
        File outFtlFile = new File(outTempFtlFilePath);
        //如果输出目标文件夹不存在，则创建
        if (!outFtlFile.getParentFile().exists()){
            outFtlFile.getParentFile().mkdirs();
        }


        //填充完数据的临时ftl
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFtlFile),"UTF-8"));
        //合并数据
        template.process(dataMap, writer);
        if(writer!=null){
            writer.close();
        }


        //输出文件路径
        String outFilePath = "";
        ZipFile zipFile = null;
        try {
//            Resource res = new ClassPathResource("static/exam-template/export/docx-template.docx");
//	        ZipFile zipFile = new ZipFile("c://wenda.docx");
            //ZipFile zipFile = new ZipFile(res.getFile());



            Resource resource = new ClassPathResource("static/exam-template/export/docx-template.docx");
            InputStream inputStream = resource.getInputStream();
            String templateFile = request.getServletContext().getRealPath("/export/emp/docx/template/");
            String fileName = "template.docx";
            File file = new File(templateFile, fileName);
            if (!file.exists()) {
                try {
                    boolean mkdirs = file.getParentFile().mkdirs();
                    if (!mkdirs) {
                        LOGGER.error("试题导出===》创建文件夹出现异常");
                    }
                    boolean newFile = file.createNewFile();
                    if (!newFile) {
                        LOGGER.error("试题导出===》创建文件出现异常");
                    }
                    FileUtils.copyInputStreamToFile(inputStream, file);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            zipFile = new ZipFile(file);
            Enumeration<? extends ZipEntry> zipEntrys = zipFile.entries();
            outFilePath =request.getServletContext().getRealPath("/export/upload/emp/docx/temp.docx");;
            ZipOutputStream zipout = new ZipOutputStream(new FileOutputStream(outFilePath));
            int len = -1;
            byte[] buffer = new byte[1024];
            while (zipEntrys.hasMoreElements()) {
                ZipEntry next = zipEntrys.nextElement();
                InputStream is = zipFile.getInputStream(next);
                //把输入流的文件传到输出流中 如果是word/document.xml由我们输入
                zipout.putNextEntry(new ZipEntry(next.toString()));
                if ("word/document.xml".equals(next.toString())) {
                    InputStream in = new FileInputStream(outFtlFile);
                    while ((len = in.read(buffer)) != -1) {
                        zipout.write(buffer, 0, len);
                    }
                    in.close();
                } else {
                    while ((len = is.read(buffer)) != -1) {
                        zipout.write(buffer, 0, len);
                    }
                    is.close();
                }
            }
            zipout.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return outFilePath;
    }
}